#pragma once
#include <iostream>
#include <pthread.h>
#include <cstring>
namespace LockModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            int n = ::pthread_mutex_init(&_lock, nullptr);
            if (n != 0)
            {
                // 初始化失败，处理错误
                // 使用 strerror(ret) 将错误代码转换为可读的字符串
                fprintf(stderr, "Failed to initialize mutex: %s\n", std::strerror(n));
                
            }
        }
        //不允许拷贝构造和赋值
        Mutex(const Mutex& m) = delete;
        const Mutex& operator = (const Mutex&) = delete;

        void Lock()
        {
            int n = ::pthread_mutex_lock(&_lock);
            if (n != 0)
            {
               fprintf(stderr, "Failed to lock: %s\n", std::strerror(n));
            }
        }
        void Unlock()
        {
            int n = ::pthread_mutex_unlock(&_lock);
            if (n != 0)
            {
               fprintf(stderr, "Failed to unlock: %s\n", std::strerror(n));
            }
        }
        pthread_mutex_t* LockPtr()
        {
            return &_lock;
        }
        ~Mutex()
        {
             int n = ::pthread_mutex_destroy(&_lock);
            if (n != 0)
            {
                // 初始化失败，处理错误
                // 使用 strerror(ret) 将错误代码转换为可读的字符串
                fprintf(stderr, "Failed to destroy mutex: %s\n", std::strerror(n));
            }
        }

    private:
        pthread_mutex_t _lock;
    };

    class LockGuard //守卫
    {
    public:
        LockGuard(Mutex& mtx)
        :_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex& _mtx;
    };
}